package com.yxw.live_vod_backend_boot.util;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.*;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @author Administrator
 */
@Slf4j
@Component
public class HuaWeiObsUtil {

    @Value("${spring.cloud.hwy.obs.ak}")
    private String ak;
    @Value("${spring.cloud.hwy.obs.sk}")
    private String sk;
    @Value("${spring.cloud.hwy.obs.end-point}")
    private String endPoint;
    @Value("${spring.cloud.hwy.obs.bucket-name}")
    private String bucketName;

    /**
     * 图片过期时间
     */
    @Value("${file.image.expiration-time}")
    private long fileImageExpirationTime;

    /**
     * OBS-上传文件
     * @param objectKey 具体的文件名（含存储路径）
     * @param inputStream 输入流
     * @return PutObjectResult
     */
    public String uploadFile(String objectKey, InputStream inputStream) {
         return uploadFileByObs(objectKey, inputStream);
    }

    /**
     * @param objectKey       具体的文件名（含存储路径）
     * @param inputStream 文件流
     */
    private String uploadFileByObs(String objectKey,InputStream inputStream) {
        ObsClient obsClient = null;
        try {
            obsClient = new ObsClient(ak, sk, endPoint);
            //判断桶是否存在，不存在就创建
            boolean  bucketExist= obsClient.headBucket(bucketName);
            if(!bucketExist){
                throw new BaseException("未创建OBS桶");
            }
            PutObjectResult result = obsClient.putObject(bucketName, objectKey, inputStream);
            return this.downloadFile(result.getObjectKey(), fileImageExpirationTime);
        } catch (Exception e) {
            log.error("OBS上传文件报错ObsException:{}", e.getMessage());
            throw new BaseException("上传文件失败："+e.getMessage());
        } finally {
            if (Optional.ofNullable(obsClient).isPresent()) {
                try {
                    obsClient.close();
                } catch (IOException e) {
                    log.error("OBS关闭连接报错！===============" + e.getMessage());
                }
            }
        }
    }

    /**
     * 删除单个对象
     * @return boolean
     */
    public boolean deleteFile(String objectKey) {
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        DeleteObjectResult deleteObjectResult = obsClient.deleteObject(bucketName, objectKey);
        boolean deleteMarker = deleteObjectResult.isDeleteMarker();
        try {
            obsClient.close();
        } catch (IOException e) {
            log.error("华为OBS关闭客户端失败", e);
        }
        return deleteMarker;
    }

    /**
     * OBS-下载文件（获取对象）
     * @param objectKey 具体的文件名（含存储路径）
     * @return ObsObject
     */
    public String downloadFile(String objectKey,long expirationTime) {
        ObsClient obsClient = null;
        try {
            obsClient = new ObsClient(ak, sk, endPoint);
            TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, expirationTime);
            request.setBucketName(bucketName);
            request.setObjectKey(objectKey);
            TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
            if(ObjectUtils.isEmpty(response.getSignedUrl())){
                log.error("获取临时文件失败" + response);
                throw new BaseException("获取临时文件失败");
            }
            return response.getSignedUrl();
        } catch (ObsException e) {
            log.error("OBS上传文件报错ObsException===============" + e.getMessage());
        } catch (Exception e) {
            log.error("OBS下载文件报错Exception===============" + e.getMessage());
        } finally {
            if (obsClient != null) {
                try {
                    obsClient.close();
                } catch (IOException e) {
                    log.error("OBS关闭连接报错！===============" + e.getMessage());
                }
            }
        }
        return null;
    }
}
